﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace kpi.Account
{
    public partial class Register : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            RegisterUser.ContinueDestinationPageUrl = Request.QueryString["ReturnUrl"];
        }

        protected void RegisterUser_CreatedUser(object sender, EventArgs e)
        {
            FormsAuthentication.SetAuthCookie(RegisterUser.UserName, false /* createPersistentCookie */);

            //调用方法，将注册用户加入User组。
            SQLProcedure_AddUsersToRoles(RegisterUser.UserName, "user");

            string continueUrl = RegisterUser.ContinueDestinationPageUrl;
            if (String.IsNullOrEmpty(continueUrl))
            {
                continueUrl = "~/";
            }
            Response.Redirect(continueUrl);
        }

        protected String GetSqlConnectionString()
        {
            return "Data Source=192.168.0.241;Initial Catalog=kpi_aspnet_db;Persist Security Info=True;User ID=sa;Password=My.SA";
        }

        protected SqlConnection GetSqlConnection()
        {
            SqlConnection SqlConnection = new SqlConnection(GetSqlConnectionString());
            return SqlConnection;
        }

        protected void SQLProcedure_AddUsersToRoles(String UserName, String RoleName)
        {
            //执行存储过程aspnet_UsersInRoles_AddUsersToRoles，将注册用户加入User组。

            SqlConnection sqlConnection = GetSqlConnection();
            sqlConnection.Open();

            SqlCommand sqlCommand = new SqlCommand("aspnet_UsersInRoles_AddUsersToRoles", sqlConnection);
            sqlCommand.CommandType = CommandType.StoredProcedure;
            sqlCommand.Parameters.Add("@ApplicationName", SqlDbType.NVarChar, 256);
            sqlCommand.Parameters.Add("@UserNames", SqlDbType.NVarChar, 4000);
            sqlCommand.Parameters.Add("@RoleNames", SqlDbType.NVarChar, 4000);
            sqlCommand.Parameters.Add("@CurrentTimeUtc", SqlDbType.DateTime);

            sqlCommand.Parameters["@ApplicationName"].Value = "/";
            sqlCommand.Parameters["@UserNames"].Value = UserName;
            sqlCommand.Parameters["@RoleNames"].Value = RoleName;
            sqlCommand.Parameters["@CurrentTimeUtc"].Value = DateTime.Now;

            sqlCommand.ExecuteNonQuery();

            sqlConnection.Close();            
        }

    }
}
